import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getInfo } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router/index'

const state = {
  token: getToken(),
  userInfo: {},
  routes: constantRoutes
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  REMOVE_TOKEN: (state) => {
    state.token = ''
    removeToken()
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_ROUTES: (state, routes) => {
    state.routes = [...constantRoutes, ...routes] // 静态路由 + 动态路由
  }
}

const actions = {
  // 登录并保存token
  async login(content, obj) {
    const data = await login(obj)
    content.commit('SET_TOKEN', data)
  },
  // 获取用户信息
  async getInfo(content) {
    const data = await getInfo()
    content.commit('SET_USERINFO', data)
    return data.roles
  },
  // 退出登录并移出token
  logout(content) {
    content.commit('REMOVE_TOKEN')
    content.commit('SET_USERINFO', {})
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
